﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Dicide.ViewModels
{
    public abstract class ConductorViewModel : ComponentViewModel
    {
        public override void UpdateOutputs()
        {
            LeftOutput = HasLeftConnector && On;
            TopOutput = HasTopConnector && On;
            RightOutput = HasRightConnector && On;
            BottomOutput = HasBottomConnector && On;
        }

        protected abstract IEnumerable<ConductorViewModel> NeighboringConductors();

        public virtual void DisconnectConductors()
        {
            if (_conductorsViewModel != null)
            {
                _conductorsViewModel.DisconnectConductors();
                _conductorsViewModel = null;
            }

            UpdateHasConnectors();
        }

        public virtual void ConnectConductors()
        {
            if (_conductorsViewModel == null)
            {
                ConnectConductors(new ConductorsViewModel());
            }
        }

        protected void ConnectConductors(ConductorsViewModel conductorsViewModel)
        {
            if (_conductorsViewModel == null)
            {
                _conductorsViewModel = conductorsViewModel;
                _conductorsViewModel.Add(this);

                foreach (var neighboringConductor in NeighboringConductors())
                {
                    neighboringConductor.ConnectConductors(conductorsViewModel);
                }
            }
        }

        Boolean _drivenOn;
        public Boolean DrivenOn
        {
            get { return _drivenOn; }
            set
            {
                SetProperty<Boolean>(ref _drivenOn, value);
                UpdateOutputs();
            }
        }

        public override void OnInputsChanged()
        {
            base.OnInputsChanged();

            if (_conductorsViewModel != null)
            {
                var drivenOn = false;

                if (_leftInput && !_conductorsViewModel.Contains(Left))
                {
                    drivenOn = true;
                }
                else if (_topInput && !_conductorsViewModel.Contains(Top))
                {
                    drivenOn = true;
                }
                else if (_rightInput && !_conductorsViewModel.Contains(Right))
                {
                    drivenOn = true;
                }
                else if (_bottomInput && !_conductorsViewModel.Contains(Bottom))
                {
                    drivenOn = true;
                }

                DrivenOn = drivenOn;
            }
        }

        ConductorsViewModel _conductorsViewModel;
    }
}
